package me.minecraft.plugin.itemrecycle.util;

import lg.minecraft.plugin.entityclear.component.EntityFilter;
import lg.minecraft.plugin.entityclear.component.EntityRemover;
import lg.minecraft.plugin.entityclear.parser.ParserContext;
import me.minecraft.plugin.itemrecycle.manager.DropItemManager;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Item;
import org.bukkit.inventory.ItemStack;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author langle__
 * @version 1.0
 */
public class ComponentUtil {

    public static EntityFilter createItemRecycleFilter(ParserContext context) {
        ConfigurationSection config = context.getConfig();
        List<Material> list;
        if (config == null) {
            list = Collections.emptyList();
        } else {
            list = new ArrayList<>();
            for (String string : config.getStringList("list")) {
                Material material = Material.matchMaterial(string);
                if (material == null) {
                    context.getLogger().warning("Invalid item name: " + string);
                    continue;
                }
                list.add(material);
            }
        }
        return entity -> {
            if (entity.getType() != EntityType.DROPPED_ITEM) return false;
            if (!(entity instanceof Item)) return false;
//            Item item = (Item) entity;
//            ItemStack stack = item.getItemStack();
//            Material material = stack.getType();
//            return list.contains(material);
            return true;
        };
    }

    public static EntityRemover createItemRecycleRemover(ParserContext context) {
        return entity -> {
            if (entity.getType() != EntityType.DROPPED_ITEM) return false;
            if (!(entity instanceof Item)) return false;
            Item item = (Item) entity;
            ItemStack stack = item.getItemStack();
            DropItemManager.INSTANCE.addDropItem(stack);
            entity.remove();
            return true;
        };
    }

}
